package com.zhuiyun.project.security.commonhandler;

import com.zhuiyun.project.utils.ObjectUtils;
import com.zhuiyun.project.utils.RedisUtil;
import org.springframework.security.authentication.AuthenticationServiceException;

import javax.servlet.http.HttpServletRequest;


/**
 * @ClassName SecurityLoginUserVerification
 * @Description 封装并验证用户信息
 * @Author zcy
 * @Date 2023/4/7 11:38
 **/
public class SecurityLoginUserVerification {

    /**
     * 封装各种登录时登录信息
     * @param request
     * @return
     */
    public static SecurityLoginUser getLoginUser(HttpServletRequest request){
        SecurityLoginUser securityLoginUser = new SecurityLoginUser();
        // 获取参数
        String username = getParams(request.getParameter("username"));
        String password =  getParams(request.getParameter("password"));
        String code =  getParams(request.getParameter("code"));
        String uuid =  getParams(request.getParameter("uuid"));
        // 封装对象信息
        securityLoginUser.setUsername(username);
        securityLoginUser.setPassword(password);
        securityLoginUser.setCode(code);
        securityLoginUser.setUuid(uuid);
        return securityLoginUser;
    }

    /**
     * 参数为null 时替换为“”  将参数中的空格去掉
     * @param params
     * @return
     */
    public static String getParams(String params){
        params =  params==null?"":params.trim();
        return params;
    }


    /**
     * 验证参数并抛出异常
     * @param params
     * @param errMsg 异常信息
     */
    public static void  vitParams(Object params,String errMsg){
        if(!ObjectUtils.isNotEmpty(params)){
            throw  new AuthenticationServiceException(errMsg);
        }
    }

    /**
     * 验证redis key
     * @param key
     * @param errMsg
     */
    public static void VitRedisKey(String key, String errMsg) {
        if(!RedisUtil.hasKey(key)){
            throw new AuthenticationServiceException(errMsg);
        }
    }

    /**
    * @Description 验证 登录验证码是否正确
    * @Author lzy
    * @Date 2023/6/15 20:06
    * @Return void
    * @param key
    * @param code
    * @param errMsg
    */
    public static void VitCode(String key, String code, String errMsg) {
        if(!RedisUtil.get(key).equals(code)){
            throw new AuthenticationServiceException(errMsg);
        }
    }

}
